<?php
//by ajsong 172403414@qq.com 2015/06/29

class chat extends core {
	public function __construct() {
		parent::__construct();
	}

	//微信端首页
	public function index() {
		$debug = isset($_GET['debug']) ? $_GET['debug'] : '';
		if ($debug) {
			require_once(FRAMEWORK_PATH . "/class/emchat/Easemob.class.php");
			$options = array(
				"client_id" => $this->easemob_client_id,
				"client_secret" => $this->easemob_client_secret,
				"org_name" => $this->easemob_org_name,
				"app_name" => $this->easemob_app_name,
			);
			$easmob = new Easemob($options);
			$ql="select+*+where+from='{$this->member_id}'+order+by+timestamp+desc";
			$rs = $easmob->chatRecord($ql,100);
			$entities = $rs['entities'];
			//$entities = array_reverse($entities);
			exit(json_encode($entities));
		}

		$token = isset($_SESSION['webim_token']) ? $_SESSION['webim_token'] : '';
		$result = array();
		if ($this->member_id>0) {
			mysql_query("SET NAMES 'utf8mb4'");
			$sql = "SELECT add_time FROM {$this->tbp}chat WHERE `from`='{$this->member_id}' ORDER BY timestamp DESC";
			$add_time = $this->db->get_var($sql);
			if (!$add_time || $add_time<time()-60*60) {
				$sql = "DELETE FROM {$this->tbp}chat WHERE `from`='{$this->member_id}'";
				$this->db->query($sql);

				require_once(FRAMEWORK_PATH . "/class/emchat/Easemob.class.php");
				$options = array(
					"client_id" => $this->easemob_client_id,
					"client_secret" => $this->easemob_client_secret,
					"org_name" => $this->easemob_org_name,
					"app_name" => $this->easemob_app_name,
				);
				$easmob = new Easemob($options);
				$ql="select+*+where+from='{$this->member_id}'+order+by+timestamp+desc";
				$rs = $easmob->chatRecord($ql,100);
				$entities = $rs['entities'];
				$entities = array_reverse($entities);
				//exit(json_encode($entities));
				foreach ($entities as $g) {
					$payload = urldecode(json_encode(url_encode($g['payload'])));
					$t = $g['timestamp'];
					$sql = "INSERT INTO {$this->tbp}chat (msg_id, `from`, `to`, payload, timestamp, add_time)
						VALUES ('".$g['msg_id']."', '".$g['from']."', '".$g['to']."',
						'".$payload."', '".substr($t, 0, strlen($t)-3)."', '".time()."')";
					$this->db->query($sql);
				}
			}
			$sql = "SELECT * FROM (SELECT * FROM {$this->tbp}chat WHERE `from`='{$this->member_id}' ORDER BY timestamp DESC) as tmpTable
				GROUP BY `to` ORDER BY timestamp DESC";
			$result = $this->db->get_results($sql);
			foreach ($result as $k=>$g) {
				$sql = "SELECT * FROM {$this->tbp}chat WHERE (`from`='{$g->from}' AND `to`='{$g->to}')
					OR (`from`='{$g->to}' AND `to`='{$g->from}') ORDER BY timestamp DESC";
				$row = $this->db->get_row($sql);
				$payload = json_decode($row->payload);
				$msg = '';
				switch ($payload->bodies[0]->type) {
					case 'txt':$msg = $payload->bodies[0]->msg;break;
					case 'img':$msg = '[图片]';break;
					case 'loc':$msg = '[位置]';break;
					case 'audio':$msg = '[语音]';break;
					case 'video':$msg = '[视频]';break;
					case 'file':$msg = '[文件]';break;
				}
				$payload->bodies[0]->msg = $msg;
				$result[$k]->payload = $payload;
				$result[$k]->timestamp = get_time_word($row->timestamp);
			}
		}
		success(array('token'=>$token, 'result'=>$result));
	}

	//保存WebIM成功登录后的accessToken
	public function save_token() {
		$token = isset($_POST['token']) ? $_POST['token'] : '';
		$_SESSION['webim_token'] = $token;
	}

	//聊天界面发送语音
	public function sendAudio() {
		require_once(FRAMEWORK_PATH . '/wxapi/config.php');
		$media_id = isset($_GET['media_id']) ? trim($_GET['media_id']) : '';
		if (!$media_id) error('缺少media_id');
		//下载微信语音
		$wxapi = new wechatCallbackAPI();
		$access_token = $wxapi->access_token();
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
		$data = $wxapi->downloadFile($url);
		$savename = time() . '.' . ($data['header']['content_type'] == 'audio/amr' ? 'amr' : 'mp3');
		$path = $_SERVER['DOCUMENT_ROOT'].'/uploadfiles/record/'.date('Y').'/'.date('m').'/'.date('d').'/';
		$wxapi->makeDir('uploadfiles/record/'.date('Y').'/'.date('m').'/'.date('d').'/');
		$filePath = $path.$savename;
		$handle = fopen($filePath, 'w');
		fwrite($handle, $data['body']);
		fclose($handle);
		$record_url = 'http://'.$_SERVER['SERVER_NAME'].'/uploadfiles/record/'.$savename;
		//环信
		require_once(FRAMEWORK_PATH . "/class/emchat/Easemob.class.php");
		$options = array(
			"client_id" => $this->easemob_client_id,
			"client_secret" => $this->easemob_client_secret,
			"org_name" => $this->easemob_org_name,
			"app_name" => $this->easemob_app_name
		);
		$easmob = new Easemob($options);
		$result = $easmob->uploadFile($filePath);
		$result = json_decode($result, true);
		success(array('url'=>$result['uri'].'/'.$result['entities'][0]['uuid'], 'secret'=>$result['entities'][0]['share-secret']));
	}

	//聊天界面
	public function talk() {
		$isKefu = true;
		$username = isset($_GET['username']) ? trim($_GET['username']) : ($isKefu?'lotus':'');
		$goods_id = isset($_GET['goods_id']) ? trim($_GET['goods_id']) : '';
		if (!$username) error('数据错误');
		if ($this->member_id<=0) {
			header("location: wap.php?app=member&act=index");
			exit;
		}
		$token = isset($_SESSION['webim_token']) ? $_SESSION['webim_token'] : '';
		//获取对方名称和头像
		$chatter_name = '';
		$chatter_avatar = '';
		$sql = "SELECT name, avatar FROM {$this->tbp}member WHERE id='{$username}'";
		$to = $this->db->get_row($sql);
		if ($to) {
			$chatter_name = $to->name;
			$chatter_avatar = $to->avatar;
		}
		mysql_query("SET NAMES 'utf8mb4'");
		$sql = "SELECT * FROM {$this->tbp}chat WHERE (`from`='{$this->member_id}' AND `to`='{$username}')
			OR (`from`='{$username}' AND `to`='{$this->member_id}') ORDER BY timestamp ASC LIMIT 100";
		$result = $this->db->get_results($sql);
		if ($result) {
			foreach ($result as $k=>$g) {
				$result[$k]->payload = json_decode($g->payload);
				$result[$k]->timestamp = get_time_word($g->timestamp);
			}
		}
		success(array("token"=>$token, "chatter_name"=>$chatter_name, "chatter_avatar"=>$chatter_avatar, "result"=>$result));
	}

	//插入聊天记录
	public function insert() {
		$msg_id = isset($_POST['msg_id']) ? trim($_POST['msg_id']) : '';
		$from = isset($_POST['from']) ? trim($_POST['from']) : $this->member_id;
		$to = isset($_POST['to']) ? trim($_POST['to']) : $this->member_id;
		$payload = isset($_POST['payload']) ? trim($_POST['payload']) : '';
		$time = time();
		$sql = "INSERT INTO {$this->tbp}chat (msg_id, `from`, `to`, payload, timestamp, add_time)
			VALUES ('{$msg_id}', '{$from}', '{$to}', '{$payload}', '{$time}', '{$time}')";
		$this->db->query($sql);
		success('ok');
	}

	//删除列表
	public function delete() {
		$id = isset($_POST['id']) ? $_POST['id'] : 0;
		if ($id<=0 || $this->member_id<=0) error('数据错误');
		$sql = "SELECT * FROM {$this->tbp}chat WHERE id='{$id}'";
		$row = $this->db->get_row($sql);
		if ($row) {
			$sql = "DELETE FROM {$this->tbp}chat WHERE (`from`='{$row->from}' AND `to`='{$row->to}')
				OR (`from`='{$row->to}' AND `to`='{$row->from}')";
			$this->db->query($sql);
		}
		success('ok');
	}

	//发送聊天
	public function send() {
		$from = isset($_POST['from']) ? $_POST['from'] : '';
		$from_id = isset($_POST['from_id']) ? $_POST['from_id'] : '';
		$chatter = isset($_POST['chatter']) ? $_POST['chatter'] : '';
		$content = isset($_POST['content']) ? $_POST['content'] : '';
		if ($chatter != '') {
			$sql = "SELECT udid FROM {$this->tbp}member WHERE id='{$chatter}'";
			$udid = $this->db->get_var($sql);
			if ($udid!='') $this->notify->send($udid, "{$from}:{$content}", "", "", array("chatter"=>$from_id, "type"=>"chat"));
			//writeLog("chatter：{$chatter}\nudid：{$udid}\ncontent：{$content}", "notification_log.txt");
		}
		success('ok');
	}

}
